<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/21
 * Time: 21:39
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\service\UserToken;
use app\api\service\Token as TokenService;
use app\api\validate\TokenGet;
use app\lib\exception\UserException;
use think\Controller;
use app\api\model\User as UserModel;
use think\Cache;
use app\lib\exception\SuccessMessage;
class Token extends BaseController
{
    public function getToken($code = ''){
        (new TokenGet()) ->goCheck();
        $ut = new UserToken($code);
        $token = $ut->get();
        //最好返回一个序列数组，tp5默认转为json
        $vip = $this->getVip($token);
        return [
            'token' => $token,
            'vip' => $vip
        ];
    }

    public function getVip($token){
        $vars = Cache::get($token);
        $varsArray = [];
        if(!is_array($vars)) {
            $varsArray = json_decode($vars,true);
        }
        if(array_key_exists('vip', $varsArray)) {
            $vip =  $varsArray['vip'];
        }else{
            $vip = '0';
        }
        return $vip;
    }

    public function setVip($token) {
        $uid = TokenService::getCurrentTokenVar('uid');
        UserModel::where('id','=',$uid)->Update(['vip'=>1]);
        return json(new SuccessMessage([
            'msg' => '更新为vip用户成功'
        ]),201);
    }
}